<?php if (!defined('BASEPATH')) exit('No direct script access allowed');

/**
 * 即时聊天模块控制器
 */
class Chats extends MY_Controller {

    function __construct() {
        parent::__construct();
        $this->load->model('bbs_user_model');
        $this->load->model('bbs_dialog_model');
        $this->assign("module", "message");
        if(!$this->userinfo){//访问超时，请重新登录
             web_redirect("account/login.html".$this->get_next_request_url());
        }
        
    }
    function index($user){
        $dialog_user = $this->bbs_user_model->get_user_by_condition(array("salt"=>$user));
        if(!$dialog_user){
            header("Location:http://www.tan66.com/error.html");exit;
        }
        $dialog_user['space_url'] = web_url('u/'.encrypt_user_id($dialog_user['user_id']));
        $dialog_user['signature'] = $dialog_user['signature'] ? $dialog_user['signature'] : "这个人好懒，什么也没有写～";
        //获取聊天室
        $dialog_room = $this->bbs_dialog_model->get_dialog_room(array("dialog_from"=>$this->bbs_userinfo['user_id'],"dialog_to"=>$dialog_user['user_id']));
        $message_list = array();
        if($dialog_room){
            $message_list = $this->bbs_dialog_model->get_message_list("((sender_to_id = ".$this->bbs_userinfo['user_id']." AND is_show = 0) or (sender_from_id = ".$this->bbs_userinfo['user_id'].")) AND room_name = '".$dialog_room['room_name']."'",0,10);
            //更新所有私信为已读
            $this->bbs_dialog_model->update_message(array("sender_from_id"=>$dialog_user['user_id'],"sender_to_id"=>$this->bbs_userinfo['user_id']),array("is_read"=>1));
        }else{
            //创建聊天室
            $room_name = random_string('alnum', 6);
            $dialog_room = array(
                0=>array("room_name"=>$room_name,"dialog_from"=>$this->bbs_userinfo['user_id'],"dialog_to"=>$dialog_user['user_id'],"is_del"=>0,"is_show"=>0),
                1=>array("room_name"=>$room_name,"dialog_from"=>$dialog_user['user_id'],"dialog_to"=>$this->bbs_userinfo['user_id'],"is_del"=>0,"is_show"=>0)
            );
            $this->bbs_dialog_model->insert_dialog_room($dialog_room);
        }
        if($message_list){
            $message_list = $this->arr_to_sort_by_create_time($message_list);
        }
        foreach ($message_list as $key=>$val){
            $message_list[$key]['time_mark'] = $val['time_mark'] ? date("Y-m-d H:i:s",$val['time_mark']) : 0;
            $message_list[$key]['is_self'] = $val['sender_from_id'] == $this->bbs_userinfo['user_id'] ? 1 : 0;
            $message_list[$key]['dialog_space_url'] = web_url("u/".encrypt_user_id($dialog_user['user_id']));
            $message_list[$key]['self_space_url'] = web_url("u/".encrypt_user_id($this->bbs_userinfo['user_id']));
        }
        $load_more_url = web_url("chats/".$user."/chat_message")."?max_timestamp=".($message_list[0]['create_time']);
        $this->assign("load_more_url", $load_more_url);
        $this->assign("message_list", $message_list);
        $this->assign("message_counts", count($message_list));
        $this->assign("to_user",  json_encode(array("uuid"=>encrypt_user_id($dialog_user['user_id']),"headImg"=>$dialog_user['head_img'])));
        $this->assign("from_user",  json_encode(array("uuid"=>encrypt_user_id($this->bbs_userinfo['user_id']),"headImg"=> $this->bbs_userinfo['head_img'])));
        $this->assign("dialog_user", $dialog_user);
        $this->display('chats/index.html');
    }
    //聊天信息（获取，发送）
    function chat_message($user){
        $dialog_user = $this->bbs_user_model->get_user_by_condition(array("salt"=>$user));
        if(!$dialog_user){
            echo json_encode(array());exit;
        }
        //获取聊天室
        $dialog_room = $this->bbs_dialog_model->get_dialog_room(array("dialog_from"=>$dialog_user['user_id'],"dialog_to"=>$this->bbs_userinfo['user_id']));
        //查询更多
        if($_GET['max_timestamp']){
            $max_timestamp = $_GET['max_timestamp'];//查询起止时间
            $message_list = $this->bbs_dialog_model->get_message_list("((sender_to_id = ".$this->bbs_userinfo['user_id']." AND is_show = 0) or (sender_from_id = ".$this->bbs_userinfo['user_id'].")) AND room_name = '".$dialog_room['room_name']."' and create_time < $max_timestamp",0,10);
            if($message_list){
                $message_list = $this->arr_to_sort_by_create_time($message_list);
            }
            $str = "";
            foreach ($message_list as $key=>$val){
                if($val['time_mark']){
                    $str .= "<p class='dialogue-time tc'>－ ". date("Y-m-d H:i:s",$val['time_mark'])." －</p>";
                }
                $is_self = $val['sender_from_id'] == $this->bbs_userinfo['user_id'] ? 1 : 0;
                if($is_self){
                    $str .= "<li class='dialogue-right' data-timestamp='".$val['create_time']."'>";
                    $str .= "<div class='header fr ml10'><img src='".$this->bbs_userinfo['head_img']."'/></div>";
                    $str .= "<div class='dialogue-txt fr'>".$val['content']."</div><div class='clear'></div></li>";
                }else{
                    $str .= "<li class='dialogue-left' data-timestamp='".$val['create_time']."'>";
                    $str .= "<div class='header fl mr10'><img src='".$dialog_user['head_img']."'/></div>";
                    $str .= "<div class='dialogue-txt fl'>".$val['content']."</div><div class='clear'></div></li>";
                }
            }
            
            $mess['reqStatus'] = true;
            $mess['data'] = array(
                "str" => $str,
                "flag" => count($message_list) < 10 ? 0 : 1,
                "url" => web_url("chats/".$user."/chat_message")."?max_timestamp=".($message_list[0]['create_time']),
            );
            echo json_encode($mess,JSON_HEX_TAG);die;
        }
        
        $since_timestamp = isset($_GET['since_timestamp']) && $_GET['since_timestamp'] != "undefined" ? trim($_GET['since_timestamp']) : time()+1;
        if($_GET['since_timestamp']){
            //更新所有私信为已读
            $this->bbs_dialog_model->update_message(array("sender_from_id"=>$dialog_user['user_id'],"sender_to_id"=>$this->bbs_userinfo['user_id']),array("is_read"=>1));
            
            $message_list = $this->bbs_dialog_model->get_message_list("((sender_to_id = ".$this->bbs_userinfo['user_id']." AND is_show = 0) or (sender_from_id = ".$this->bbs_userinfo['user_id'].")) AND room_name = '".$dialog_room['room_name']."' and create_time > $since_timestamp",0,10);
            if($message_list){
                $message_list = $this->arr_to_sort_by_create_time($message_list);
            }
            $str = "";
            foreach ($message_list as $key=>$val){
                if($val['time_mark']){
                    $str .= "<p class='dialogue-time tc'>－ ".  date("Y-m-d H:i:s",$val['time_mark'])." －</p>";
                }
                $is_self = $val['sender_from_id'] == $this->bbs_userinfo['user_id'] ? 1 : 0;
                if($is_self){
                    
                    $str .= "<li class='dialogue-right' data-timestamp='".$val['create_time']."'>";
                    $str .= "<div class='header fr ml10'><img src='".$this->bbs_userinfo['head_img']."'/></div>";
                    $str .= "<div class='dialogue-txt fr'>".$val['content']."</div></li>";
                    
                }else{
                    $str .= "<li class='dialogue-left' data-timestamp='".$val['create_time']."'>";
                    $str .= "<div class='header fl mr10'><img src='".$dialog_user['head_img']."'/></div>";
                    $str .= "<div class='dialogue-txt fl'>".$val['content']."</div></li>";
                }
            }
            
            echo json_encode($str ? array("str"=>$str) : array(),JSON_HEX_TAG);die;
        }
    }
    
    function send_message($user){
        $dialog_user = $this->bbs_user_model->get_user_by_condition(array("salt"=>$user));
        if(!$dialog_user){
            echo json_encode(array());exit;
        }
        //获取聊天室
        $dialog_room = $this->bbs_dialog_model->get_dialog_room(array("dialog_from"=>$this->bbs_userinfo['user_id'],"dialog_to"=>$dialog_user['user_id']));
        
        $action = isset($_POST['act']) ? trim($_POST['act']) : "";
        if($action == "send"){
            $content = trim($_POST['message']);
            $send_time = trim($_POST['send_timestamp']);
            if(!$content){
                $mess['reqStatus'] = false;
                $mess['errorCode'] = 1001;
                $mess['errorMsg'] = "内容不能为空哦！";
                echo JSON($mess);exit;
            }
            if(!$dialog_room){
                //创建聊天室
                $room_name = random_string('alnum', 6);
                $dialog_room = array(
                    0=>array("room_name"=>$room_name,"dialog_from"=>$this->bbs_userinfo['user_id'],"dialog_to"=>$dialog_user['user_id'],"is_del"=>0,"is_show"=>0),
                    1=>array("room_name"=>$room_name,"dialog_from"=>$dialog_user['user_id'],"dialog_to"=>$this->bbs_userinfo['user_id'],"is_del"=>0,"is_show"=>0)
                );
                $this->bbs_dialog_model->insert_dialog_room($dialog_room);
            }
            
            
            $current_time = time();
            $data = array();
            $data['room_name'] = $dialog_room['room_name']? $dialog_room['room_name']:$room_name;
            $data['sender_from_id'] = $this->bbs_userinfo['user_id'];
            $data['sender_to_id'] = $dialog_user['user_id'];
            $data['create_time'] = $current_time;
            $data['content'] = $content;
            $data['is_read'] = 0;
            $data['is_show'] = 0;
            //如果对方屏蔽聊天，则不插入私信内容
            if($dialog_room['is_show']){
                $data['is_show'] = 1;//屏蔽消息
                $data['is_read'] = 1;
            }
            
            if($dialog_room['is_del']){//如果删除了聊天
                $this->db->query("update tan_bbs_user_dialog_room set is_del = 0 where id = ".$dialog_room['id']);
            }
            
            //获取最新一条信息
            $lastest_message = $this->bbs_dialog_model->get_message(array("room_name"=>$dialog_room['room_name']? $dialog_room['room_name']:$room_name));
            //3分钟标记时间
            $data['time_mark'] = !$lastest_message ? $current_time : (($current_time - $lastest_message['create_time']) > 180 ? $current_time : 0);
            $this->bbs_dialog_model->insert_message($data);
            $str = "";
            if($data['time_mark']){
                $str .= "<p class='dialogue-time tc'>－ ". date("Y-m-d H:i:s",$data['time_mark'])." －</p>";
            }
            $str .= "<li class='dialogue-right' data-timestamp='".$data['create_time']."'>";
            $str .= "<div class='header fr ml10'><img src='".$this->bbs_userinfo['head_img']."'/></div>";
            $str .= "<div class='dialogue-txt fr'>".$data['content']."</div></li>";
                
            $mess['reqStatus'] = true;
            $mess['data'] = array("mess"=>$str);
            echo json_encode($mess,JSON_HEX_TAG);die;
        }
    }
    private function arr_to_sort_by_create_time($arr){
        $create_time_arr = array();
        foreach ($arr as $key =>$val){
            $create_time_arr[$key] = $val['create_time'];
        }
        array_multisort($create_time_arr,SORT_ASC,$arr);
        return $arr;
    }
}
